package com.apotik.legenda.dialog;

import javax.swing.JDialog;

import com.apotik.legenda.dao.RoleDao;
import com.apotik.legenda.dao.UserDao;
import com.apotik.legenda.model.Role;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.GeneralObserver;
import com.apotik.legenda.util.CalendarUtil;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;

import java.awt.GridLayout;

import javax.swing.JLabel;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.JComboBox;
import javax.swing.JButton;

/**
 * @author Makhsus Bilmajdi
 */
public class AddEditUserDialog extends JDialog implements ActionListener {
	private static final long serialVersionUID = 1L;
	
	private List<Role> roleList;
	private User currentUser;
	
	private JTextField textFieldFullname;
	private JTextField textFieldHp;
	private JTextField textFieldUsername;
	private JTextField textFieldPassword;
	private JTextArea textAreaAlamat;
	private JButton btnCancel;
	private JButton btnSubmit;
	private JPanel panelBtn;
	
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxRoles;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxActive;
	
	private GeneralObserver observer;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public AddEditUserDialog(GeneralObserver observer) {
		this.observer = observer;
		
		setTitle("Add New User");
		setSize(370, 360);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(3, 5, 3, 5));
		panel_1.add(panel_2, BorderLayout.NORTH);
		panel_2.setLayout(new GridLayout(0, 2, 0, 4));
		
		JLabel lblFullname = new JLabel("Nama Lengkap");
		lblFullname.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(lblFullname);
		
		textFieldFullname = new JTextField();
		textFieldFullname.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_2.add(textFieldFullname);
		textFieldFullname.setColumns(10);
		
		JLabel lblUsername = new JLabel("Username");
		lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(lblUsername);
		
		textFieldUsername = new JTextField();
		textFieldUsername.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_2.add(textFieldUsername);
		textFieldUsername.setColumns(10);
		
		JLabel lblPassword = new JLabel("Password");
		lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_2.add(lblPassword);
		
		textFieldPassword = new JTextField("12345");
		panel_2.add(textFieldPassword);
		textFieldPassword.setColumns(10);
		
		JLabel lblSetActive = new JLabel("Set Active");
		lblSetActive.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(lblSetActive);
		
		comboBoxActive = new JComboBox();
		comboBoxActive.setModel(new DefaultComboBoxModel(new String[] {"YES", "NO"}));
		panel_2.add(comboBoxActive);
		
		JLabel lblHandphone = new JLabel("Handphone");
		lblHandphone.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(lblHandphone);
		
		textFieldHp = new JTextField();
		textFieldHp.setFont(new Font("Tahoma", Font.PLAIN, 12));
		panel_2.add(textFieldHp);
		textFieldHp.setColumns(10);
		
		JLabel lblRole = new JLabel("Role");
		lblRole.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(lblRole);
		
		comboBoxRoles = new JComboBox();
		comboBoxRoles.setFont(new Font("Tahoma", Font.PLAIN, 12));
		comboBoxRoles.setModel(comboboxModelRoles());
		panel_2.add(comboBoxRoles);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new EmptyBorder(3, 5, 3, 5));
		panel_1.add(panel_3);
		panel_3.setLayout(new GridLayout(0, 2, 0, 4));
		
		JLabel lblAlamat = new JLabel("Alamat");
		lblAlamat.setVerticalAlignment(SwingConstants.TOP);
		panel_3.add(lblAlamat);
		lblAlamat.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		textAreaAlamat = new JTextArea();
		textAreaAlamat.setFont(new Font("Courier New", Font.PLAIN, 12));
		textAreaAlamat.setLineWrap(true);
		textAreaAlamat.setWrapStyleWord(true);
		//textAreaAlamat.setRows(5);
		
		JScrollPane scrollPane = new JScrollPane(textAreaAlamat);
		panel_3.add(scrollPane);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setPreferredSize(new Dimension(200, 60));
		
		JPanel panel_4 = new JPanel();
		panel.add(panel_4, BorderLayout.SOUTH);
		panel_4.setLayout(new BorderLayout(0, 0));
		
		panelBtn = new JPanel();
		panel_4.add(panelBtn, BorderLayout.EAST);
		
		btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(this);
		panelBtn.add(btnCancel);
		
		btnSubmit = new JButton("Submit");
		btnSubmit.addActionListener(this);
		panelBtn.add(btnSubmit);
	}
	
	public void editItem(User user){
		this.currentUser = user;
		this.setTitle("Edit User");
		
		textFieldUsername.setEnabled(false);
		textFieldPassword.setEnabled(false);
		
		textFieldFullname.setText(user.getFullName());
		textFieldUsername.setText(user.getUserName());
		textFieldPassword.setText("");
		textFieldHp.setText(user.getPhoneNumber()!=null ? user.getPhoneNumber():"");
		textAreaAlamat.setText(user.getAddress()!=null ? user.getAddress():"");
		
		boolean isActive = user.isActive();
		if(isActive){
			comboBoxActive.setSelectedIndex(0);
		}else{
			comboBoxActive.setSelectedIndex(1);
		}
		
		int indexForRole = 0;
		if(roleList!=null){
			if(roleList.size()>0){
				Role role = user.getRole();
				for(int i=0;i<roleList.size();i++){
					if(role.getRoleId().toString().equalsIgnoreCase(roleList.get(i).getRoleId().toString())){
						indexForRole = i+1;
					}
				}
			}
		}
		comboBoxRoles.setSelectedIndex(indexForRole);
		
	}
	
	public void detail(User user){
		this.currentUser = user;
		this.setTitle("Detail User");
		
		textFieldFullname.setText(user.getFullName());
		textFieldUsername.setText(user.getUserName());
		textFieldHp.setText(user.getPhoneNumber()!=null ? user.getPhoneNumber():"");
		textAreaAlamat.setText(user.getAddress()!=null ? user.getAddress():"");
		
		boolean isActive = user.isActive();
		if(isActive){
			comboBoxActive.setSelectedIndex(0);
		}else{
			comboBoxActive.setSelectedIndex(1);
		}
		
		int indexForRole = 0;
		if(roleList!=null){
			if(roleList.size()>0){
				Role role = user.getRole();
				for(int i=0;i<roleList.size();i++){
					if(role.getRoleId().toString().equalsIgnoreCase(roleList.get(i).getRoleId().toString())){
						indexForRole = i+1;
					}
				}
			}
		}
		comboBoxRoles.setSelectedIndex(indexForRole);
		
		textFieldFullname.setEnabled(false);
		textFieldUsername.setEnabled(false);
		textFieldPassword.setEnabled(false);
		textFieldHp.setEnabled(false);
		textAreaAlamat.setEnabled(false);
		comboBoxActive.setEnabled(false);
		comboBoxRoles.setEnabled(false);
		
		panelBtn.remove(btnSubmit);
		btnCancel.setText("OK");
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private DefaultComboBoxModel comboboxModelRoles(){
		DefaultComboBoxModel model = new DefaultComboBoxModel<>();
		model.addElement(" - Pilih Role -");
		
		RoleDao dao = new RoleDao();
		roleList = dao.loadAll(true);
		for(Role role: roleList){
			if(role!=null){
				model.addElement(role.getRoleName());
			}
		}
		
		return model;
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		
		if(source==btnCancel){
			this.setVisible(false);
		}else if(source==btnSubmit){
			String fn = textFieldFullname.getText().trim();
			String username = textFieldUsername.getText().trim();
			String password = textFieldPassword.getText().trim();
			String hp = textFieldHp.getText().trim();
			String alamat = textAreaAlamat.getText().trim();
			
			
			int selectedRoleIndex = comboBoxRoles.getSelectedIndex();
			if(selectedRoleIndex==0){
				JOptionPane.showMessageDialog(null, "Silahkan pilih Role", "Exception", JOptionPane.ERROR_MESSAGE);
				comboBoxRoles.requestFocus();
				return;
			}
			Role role = roleList.get(selectedRoleIndex-1);
			
			boolean isActive = true;
			if(comboBoxActive.getSelectedIndex()==1){
				isActive = false;
			}
			
			Calendar calNow  = CalendarUtil.calendarNow();
			User user = new User();
			if(currentUser!=null){
				user = currentUser;
				user.setUpdateDate(calNow.getTime());
			}else{
				user.setPassword(password);
				user.setCreateDate(calNow.getTime());
			}
			user.setFullName(fn);
			user.setUserName(username);
			user.setPhoneNumber(hp);
			user.setAddress(alamat);
			user.setRole(role);
			user.setActive(isActive);
			
			UserDao dao = new UserDao();
			if(dao.saveOrUpdate(user)){
				this.setVisible(false);
				
				HashMap<String, Object> hm = new HashMap<>();
				hm.put("isSuccess", true);
				observer.response(hm);
			}
				
		}
		
	}
	
	
}
